import React, { useEffect, useState } from 'react';
import AIWriter from 'react-aiwriter';

const TypingEffectComponent = () => {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const eventSource = new EventSource('http://localhost:3000/stream');
    eventSource.onmessage = function (event) {
      const data = JSON.parse(event.data);
      const { msg } = data;
      setMessages((prevMessages) => [...prevMessages, msg]);
    };

    // Clean up the event source connection when the component unmounts
    return () => {
      eventSource.close();
    };
  }, []);

  return (
    <AIWriter>
      {messages.map((message, index) => (
        <span key={index}>{message}</span>
      ))}
    </AIWriter>
  );
};

export default TypingEffectComponent;
